// 自动校验
import { WorkflowDocument, WorkflowNodeJSON, domUtils } from '@flowgram.ai/free-layout-editor';

import { initialData } from '../initial-data';

const edges = initialData.edges;
console.log(edges);

const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

export const runWorkflow = async (document: WorkflowDocument) => {
  const nodes = initialData.nodes;
  const edges = initialData.edges;

  //先清空所有节点的高亮边框
  nodes.forEach((node) => {
    clearHighlightedNode(node);
  });

  // 找到起始节点
  const startNode = nodes.find((node) => node.type === 'asset_edit');
  if (!startNode) {
    console.warn('No start node found.');
    return;
  }

  let currentNode: WorkflowNodeJSON | null = startNode; // 修改类型为可为 null

  const visited = new Set<string>();

  while (currentNode) {
    //延时1s
    await sleep(1000);
    const nodeId: string = currentNode.id;
    if (visited.has(nodeId)) break; // 避免循环

    visited.add(nodeId);

    console.log(`Running node: ${nodeId}`);
    if (currentNode.type === 'condition') {
      console.log('模拟校验失败');
      errorNode(currentNode);
    } else {
      highlightNode(currentNode); // 高亮节点
    }

    // 获取下个节点
    const outgoingEdges = edges.filter((edge) => edge.sourceNodeID === nodeId);
    if (outgoingEdges.length === 0) break;

    // 取第一个输出边（可扩展为条件判断）
    const nextNodeId = outgoingEdges[0].targetNodeID;
    currentNode = nodes.find((node) => node.id === nextNodeId) || null;
  }

  console.log('Workflow execution completed.');
};

const highlightNode = (node: WorkflowNodeJSON) => {
  const n = document.getElementById(node.id);
  if (n) {
    //直接操作dom才能避免对flowgram的渲染造成影响
    n.style.border = '2px dashed green';
  }
};

const errorNode = (node: WorkflowNodeJSON) => {
  const n = document.getElementById(node.id);
  if (n) {
    //直接操作dom才能避免对flowgram的渲染造成影响
    n.style.border = '2px dashed #23D18B';
  }
};

// 替换原第16行的 domUtils.clearHighlightedNodes(document.container);
const clearHighlightedNode = (node: WorkflowNodeJSON) => {
  const n = document.getElementById(node.id);
  if (n) {
    //直接操作dom才能避免对flowgram的渲染造成影响
    n.style.border = 'none';
  }
};
